package com.eight.travel.utils;

import com.eight.travel.pojo.Promession;
import com.eight.travel.pojo.Admin;
import com.eight.travel.service.PromessionService;
import com.eight.travel.service.AdminService;
import com.eight.travel.service.UserService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @author Q小旭
 * @version 1.0
 */
public class MyRealm extends AuthorizingRealm {

    @Autowired
    UserService userService;
    @Autowired
    PromessionService promessionService;
    @Autowired
    AdminService adminService;
    //鉴权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //获得登录昵称
        String username =(String) principalCollection.getPrimaryPrincipal();
        //根据昵称获得所有权限
        List<Promession> permissions = promessionService.findByName(username);
        //去除重复的权限
        Set<String> set = new HashSet<>();
        for (Promession permission : permissions){
            set.add(permission.getPowername());
        }
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        //设置相关权限
        simpleAuthorizationInfo.setStringPermissions(set);
        return simpleAuthorizationInfo;
    }

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        //从token中获得用户输入的昵称
        String name =(String) token.getPrincipal();
        Admin admin = adminService.findByUname(name);
//        //根据昵称获得数据库中的密码，要连接数据库
        String adminpassword = admin.getAdminpassword();
//        //返回AuthenticationInfo
        return new SimpleAuthenticationInfo(name,adminpassword,this.getName());
    }
}
